<template>
  <div>
    <Header :titleName = "titleObj" ></Header>
    <!-- 卡片区域 -->
    <el-card>
      <el-button type="primary" @click="showAddCateVisiable"
        >添加分类</el-button
      >
      <tree-table
        :data="goodsCateList"
        show-index
        :columns="columns"
        :selection-type="false"
        :expand-type="false"
        index-text="#"
        border
      >
        <!-- 是否有效 -->
        <template slot="isOk" slot-scope="scope">
          <i
            class="el-icon-success"
            v-if="scope.row.cat_deleted === false"
            style="color: green"
          ></i>
          <i class="el-icon-error" style="color: red" v-else></i>
        </template>
        <!-- 排序 -->
        <template slot="isOrder" slot-scope="scope">
          <el-tag size="mini" v-if="scope.row.cat_level === 0">一级</el-tag>
          <el-tag size="mini" v-if="scope.row.cat_level === 1" type="success"
            >二级</el-tag
          >
          <el-tag size="mini" v-if="scope.row.cat_level === 2" type="warning"
            >三级</el-tag
          >
        </template>
        <!-- 操作 -->
        <template slot="isOpt" slot-scope="scope">
          <el-button type="primary" icon="el-icon-edit" size="mini" @click="editCateInfo(scope.row.cat_id)"
            >编辑</el-button
          >
          <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteCateInfo(scope.row.cat_id)"
            >删除</el-button
          >
        </template>
      </tree-table>
      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="cateInfo.pagenum"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="cateInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 新增对话框区域 -->
    <el-dialog
      title="添加分类"
      :visible.sync="addCateVisiable"
      width="40%"
      @close="addCateClose"
    >
      <el-form
        :model="addCateForm"
        :rules="addCateRules"
        ref="addRoleRef"
        label-width="80px"
      >
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="addCateForm.cat_name"></el-input>
        </el-form-item>
        <el-form-item label="父级分类">
          <!-- options 数据源 -->
          <!-- v-model 选中的value -->
          <!-- props 展示的表达式 label value  children -->
          <!-- change 选中改变的方法-->
          <!-- clearable 小xx一键清除-->
          <!-- change-on-select 可以选中任意级别（默认只能选中最后一个级别）-->
          <el-cascader
            v-model="selectedKeys"
            :options="currentParentList"
            :props="optionsCate"
            @change="handleChange"
            clearable
            change-on-select
          >
          </el-cascader>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addCateVisiable = false">取 消</el-button>
        <el-button type="primary" @click="addCateOk">确 定</el-button>
      </span>
    </el-dialog>

      <!-- 编辑对话框区域 -->
    <el-dialog
      title="添加分类"
      :visible.sync="editCateVisiable"
      width="40%"
      @close="editCateClose"
    >
      <el-form
        :model="editCateForm"
        :rules="addCateRules"
        ref="addRoleRef"
        label-width="80px"
      >
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="editCateForm.cat_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editCateVisiable = false">取 消</el-button>
        <el-button type="primary" @click="editCateOk">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import Header from '../shard/header.vue'
export default {
  data() {
    return {
      titleObj:{ firstName:'商品管理',scendName:'分类管理'},
      // 查询参数
      cateInfo: {
        type: 3,
        pagenum: 1,
        pagesize: 5,
      },
      editCateVisiable:false,
      catId:0,// 修改的catId
      total: 0, // 总条数
      goodsCateList: [], // 数据列表
      currentParentList: [], // 父级数据列表
      columns: [
        {
          label: '分类名称',
          prop: 'cat_name',
        },
        {
          label: '是否有效',
          type: 'template',
          template: 'isOk',
        },
        {
          label: '排序',
          type: 'template',
          template: 'isOrder',
        },
        {
          label: '操作',
          type: 'template',
          template: 'isOpt',
        },
      ],
      addCateVisiable: false,
      addCateForm: {
        cat_name: '', // 分类名称
        cat_pid:0,// 父级分类id
        cat_level:0 // 分类的登记默认是 1级
      },
      editCateForm: {
        cat_name: '', // 分类名称
      },
      addCateRules: {
        cat_name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' },
        ],
      },
      optionsCate: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        expandTrigger: 'hover',
      },
      selectedKeys: [],
      iscascaderShow:0
    }
  },
  created() {
    this.getCateList()
  },
  methods: {
    async getCateList() {
      const { data: res } = await this.$http.get('/categories', {
        params: this.cateInfo,
      })
      if (res.meta.status !== 200) {
        return this.$message.error('获取分类列表失败！')
      }
      this.total = res.data.total
      //   console.log(res)
      this.goodsCateList = res.data.result
    },
    handleSizeChange(newSize) {
      this.cateInfo.pagesize = newSize
      this.getCateList()
    },
    handleCurrentChange(newPageNum) {
      this.cateInfo.pagenum = newPageNum
      this.getCateList()
    },
    showAddCateVisiable() {
      this.getCurrentParentList()
      this.addCateVisiable = true
    },
    async getCurrentParentList() {
      const { data: res } = await this.$http.get('/categories', {
        params: { type: 2 },
      })
      if (res.meta.status !== 200) {
        return this.$message.error('获取父级分类列表失败！')
      }
      this.currentParentList = res.data
      console.log(this.currentParentList)
    },
    addCateClose() {
      this.$refs.addRoleRef.resetFields();
      this.selectedKeys = []
      this.addCateForm.cat_pid = 0
      this.addCateForm.cat_level = 0
    },
    editCateClose(){
      this.editCateForm.cat_name = ""
      this.editCateVisiable = false;
    },
    addCateOk() {
      this.$refs.addRoleRef.validate( async valid =>{
        if(!valid) return;
        const {data:res} = await this.$http.post('/categories',this.addCateForm);
        if(res.meta.status != 201){
          return this.$message.error('添加分类失败')
        }
        this.$message.success('添加分类成功')
        this.getCateList();
        this.addCateVisiable = false
      })

      this.addCateVisiable = false
    },
    handleChange() {
      if(this.selectedKeys.length > 0 ){
        this.addCateForm.cat_pid = this.selectedKeys[this.selectedKeys.length - 1];
        this.addCateForm.cat_level = this.selectedKeys.length;
      }else{
        this.addCateForm.cat_pid = 0
        this.addCateForm.cat_level = 0
      }
    },
    // 修改
    async editCateInfo(catId){
      this.catId = catId
      const {data:res} = await this.$http.get('/categories/'+this.catId);
      if(res.meta.status != 200){
        return this.$message.error('获取修改信息失败')
      }
      this.editCateForm.cat_name =  res.data.cat_name
      this.editCateVisiable = true
    },
    // 修改确认
    async editCateOk(){
        this.$refs.addRoleRef.validate( async valid =>{
        if(!valid) return;
        const {data:res} = await this.$http.put('/categories/'+this.catId,this.editCateForm);
        if(res.meta.status != 201){
          return this.$message.error('修改分类失败')
        }
        this.$message.success('修改分类成功')
        this.getCateList();
        this.editCateVisiable = false
      })
    },
    // 删除
   async deleteCateInfo(catId){
     let resultConfirm =  await this.$confirm('此操作将永久删除该分类, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if(resultConfirm != "confirm"){
          return this.$message.warning('取消删除')
      }
      let {data : res} =   await this.$http.delete('/categories/'+catId)
      if (res.meta.status !== 200) {
        return this.$message.error('查询该分类失败！')
      }
      this.$message.success('删除该分类成功！')
      this.getCateList();
    }
  },
  components:{
    Header
  }
}
</script>

<style lang="less" scoped>
.el-cascader {
  width: 100%;
  height: 50px;
}
</style>>
